/*
 * 发送端（遥控器）- Arduino/ESP32
 * 功能：
 * - 连接接收端AP（esp32_motor_ap）
 * - 使用两个按钮控制正反转（GPIO25和GPIO26）
 * - 计算方向（-1/0/1）与速度（0或255），通过UDP发送到接收端 192.168.4.1:4210
 */

#include <WiFi.h>
#include <WiFiUdp.h>

// WiFi 配置（接收端作为AP热点）
const char* WIFI_SSID = "esp32_motor_ap";
const char* WIFI_PASSWORD = "12345678";

// 接收端（电机控制器）的 IP 与 UDP 端口
const char* RECEIVER_IP = "192.168.4.1";
const uint16_t UDP_PORT = 4210;

// 按钮引脚定义
const int BUTTON_FORWARD_PIN = 25;  // 正转按钮
const int BUTTON_BACKWARD_PIN = 26; // 反转按钮

WiFiUDP udp;

void connectWiFi() {
  Serial.println("正在连接接收端AP...");
  WiFi.mode(WIFI_STA);
  WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print('.');
  }
  Serial.print("\nWiFi连接成功，本机IP: ");
  Serial.println(WiFi.localIP());
}

/*
 * 读取按钮状态并转换为方向与速度
 * 逻辑：
 * - 正转按钮按下 -> direction=1, speed=255
 * - 反转按钮按下 -> direction=-1, speed=255
 * - 两个按钮都按下或都不按下 -> direction=0, speed=0
 */
void readButtons(int& direction, int& speed) {
  int forwardState = digitalRead(BUTTON_FORWARD_PIN);
  int backwardState = digitalRead(BUTTON_BACKWARD_PIN);

  if (forwardState == LOW && backwardState == HIGH) { // 正转按钮按下
    direction = 1;
    speed = 255;
  } else if (forwardState == HIGH && backwardState == LOW) { // 反转按钮按下
    direction = -1;
    speed = 255;
  } else { // 两个按钮都按下或都不按下
    direction = 0;
    speed = 0;
  }
}

void setup() {
  Serial.begin(115200);
  delay(200);
  
  // 初始化按钮引脚
  pinMode(BUTTON_FORWARD_PIN, INPUT_PULLUP);
  pinMode(BUTTON_BACKWARD_PIN, INPUT_PULLUP);
  
  connectWiFi();
}

void loop() {
  int direction = 0;
  int speed = 0;

  readButtons(direction, speed);

  // 组装并发送UDP数据包 "direction,speed"
  char packet[16];
  snprintf(packet, sizeof(packet), "%d,%d", direction, speed);

  udp.beginPacket(RECEIVER_IP, UDP_PORT);
  udp.write((uint8_t*)packet, strlen(packet));
  udp.endPacket();

  // 调试输出
  Serial.print("发送: ");
  Serial.println(packet);

  delay(50); // 约20Hz
}